//
//  CurrencyOrderViewModel.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/7/12.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CurrencyOrderViewModel: BaseViewModel {
    @objc dynamic var refreshBool:Bool = false // kvo监听
    @objc dynamic var historyRefreshBool:Bool = false
    @objc dynamic var refreshPosition:Bool = false //持仓
    var pageNo:Int = 1
    var pageSize:Int = 10
    var tradeCode = ""
    var position = 0
    
    var type:OrderType?
    
    var currentSelected:Int = 0 //0 当前 1 历史/持仓 2历史
    var historyDataArr:[CoinOrderModel] = []
    var selectOrderModel:CoinOrderModel = CoinOrderModel() //选择的model //撤销
    
    lazy var historyRequest: HistoryOrderRequest = {
        let api = HistoryOrderRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var cancelOrderRequest: CancelOrederRequest = {
        let api = CancelOrederRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var currentRequest: LeverCurrentRequest = {
        let api = LeverCurrentRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    lazy var positionRequest: LeverCurrentRequest = {
        let api = LeverCurrentRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    lazy var changePositionRequest: LeverChangeRequest = {
        let api = LeverChangeRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    //当前委托
    var currentArr:[CoinOrderModel] = []
    //持仓
    var positionArr:[CoinOrderModel] = []
    
    
    /// 获取历史委托
    ///
    /// - Parameters:
    ///   - view:
    ///   - screenBool: 标记是否是筛选
    func archiveHistoryInfo(view:UIView? = nil,screenBool:Bool = false)  {
        if view != nil {
        CYMBShow.openIndicator(message: nil, view:view)
        }
        historyRequest.isLeverHistory  = type == .leverOrderType ? true : false
        self.request(request: historyRequest, success: {[weak self] (result) in
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
            if result == nil {
                self?.historyRefreshBool = true
                return
            }
            guard let dic  = result!["data"] as? [String:Any] else {
                self?.historyRefreshBool = true
                return
            }
            guard let arr = dic["list"] as? [[String:Any]] else {
                self?.historyRefreshBool = true
                return
            }
            if self?.pageNo == 1 {
                self?.historyDataArr.removeAll()
            }
            for map in arr {
                let model = CoinOrderModel(JSON: map)
                if model != nil {
                    model?.archiveAllPrice()
                    self?.historyDataArr.append(model!)
                }
            }
            self?.historyRefreshBool = true
            
            
        }) {[weak self] (response) in
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
            if screenBool {
                self?.historyRefreshBool = true
            }
            self?.historyRefreshBool = true
        }
    }
    
    
    func archiveCurrentInfo(view:UIView? = nil) {
        if view != nil {
            CYMBShow.openIndicator(message: nil, view:view)
        }
        positionRequest.type = .leverCurrent
        self.request(request: positionRequest, success: {[weak self] (result) in
            self?.currentArr.removeAll()
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
            if result == nil {
                self?.refreshBool = true
                return
            }
            guard let arr  = result!["data"] as? [[String:Any]] else {
                self?.refreshBool = true
                return
            }
          
            for map in arr {
                let model = CoinOrderModel(JSON: map)
                if model != nil {
                    model?.archiveAllPrice()
                    self?.currentArr.append(model!)
                }
            }
            self?.refreshBool = true
            
            
        }) {[weak self] (response) in
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
           
            self?.refreshBool = true
        }
        
    }
    
    /// 获取持仓列表
    ///
    /// - Parameter view: <#view description#>
    func archivePositionInfo(view:UIView? = nil) {
        if view != nil {
            CYMBShow.openIndicator(message: nil, view:view)
        }
        currentRequest.type = .leverPosition
        self.request(request: currentRequest, success: {[weak self] (result) in
            self?.positionArr.removeAll()
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
            if result == nil {
                self?.refreshPosition = true
                return
            }
            guard let arr = result!["data"] as? [[String:Any]] else {
                self?.refreshPosition = true
                return
            }
            for map in arr {
                let model = CoinOrderModel(JSON: map)
                if model != nil {
                    model?.archiveAllPrice()
                    model?.archiveScalesPrice()
                    self?.positionArr.append(model!)
                }
            }
            self?.refreshPosition = true
            
            
        }) {[weak self] (response) in
            if view != nil {
                CYMBShow.colseIndicator(view: view)
            }
            
            self?.refreshPosition = true
        }
        
    }
    
    //平仓
    func changeLeverPosition() {
        self.request(request: changePositionRequest, success: { (result) in
            CYMBShow.showMessage("平仓状态提交成功")
            
        }) { (response) in
            if response.errorMsg.count != 0 {
            CYMBShow.showMessage(response.errorMsg)
            }
        }
    }
    
    func refreshHistory()  {
        self.pageNo = 1
        self.archiveHistoryInfo()
    }
    
    func refreshOrder(arr:[CoinOrderModel])  {
        currentArr = arr
        self.refreshBool = true
    }
    
    func cancelOrder() {
        cancelOrderRequest.isCoinOrder = self.type == .coinOrderType ? true : false
        self.request(request: cancelOrderRequest, success: {[weak self] (result) in
            if self?.selectOrderModel.status == 3 {
                CYMBShow.showMessage(kText("已在撤销中"))
            }else {
                CYMBShow.showMessage(kText("撤销委托单申请提交成功"))
            }
        }) { (response) in
            if  response.errorMsg.count != 0  {
                CYMBShow.showMessage(response.errorMsg)
            }
        }
    }
    
    func openTimer() {
        CYGCDTimer.shared.scheduledDispatchTimer(WithTimerName: "lever", timeInterval: 10, queue: .main, repeats: true) {
            self.archiveCurrentInfo()
            self.archivePositionInfo()
        }
    }
    
    func closeTimer() {
        CYGCDTimer.shared.cancleTimer(WithTimerName: "lever")
    }
    
}

extension CurrencyOrderViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        let block = self.successBlockDic.object(forKey: request.path())
        if ((block as? success) != nil) {
            (block as! success)(data)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        
    }
    
    func requestDidFail(_ request: BaseRequest) {
        let block = self.failBlockDic.object(forKey: request.path())
        if ((block as? fail) != nil) {
            (block as! fail)(request)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? HistoryOrderRequest {
            pramas.updateValue(pageNo, forKey: "pageNo")
            pramas.updateValue(10, forKey: "pageSize")
            pramas.updateValue(tradeCode, forKey: "tradeCode")
            if tradeCode.count != 0 {
                
                pramas.updateValue(position, forKey: "position")
            }
            pramas.updateValue(AppInfo.default.userId ?? 0, forKey: "userId")
        }else if let _ = request as? CancelOrederRequest {
            pramas.updateValue(AppInfo.default.userId ?? 0, forKey: "userId")
            pramas.updateValue(selectOrderModel.orderNo, forKey: "orderNo")
        }else if let _ = request as? LeverChangeRequest {
            pramas.updateValue(AppInfo.default.userId ?? 0, forKey: "userId")
            pramas.updateValue(selectOrderModel.orderNo, forKey: "orderNo")
        }
        return pramas
    }
}
